package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Flight;
import model.FlightIO;

/**
 * Servlet implementation class FlightSearchResults
 */
public class FlightSearchResults extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FlightSearchResults() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * On a post, the FlightSearchResults servlet gets the flight id from the 
	 * form. The FlightIO class is then used to get the flight. The flight is
	 * then set as a session attribute. Then it is forwarded to ViewAndBook.jsp 
	 * 
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Get session object
		HttpSession session = request.getSession();
		
		//Get flight id from form
		String input = request.getParameter("flightID");
		int flightId = Integer.parseInt(input);
		
		//Get flight from flight id
		FlightIO flightIO = new FlightIO();
		String classType = (String) session.getAttribute("classType");

		Flight flight = flightIO.getFlight(flightId);
		
		int seats = (int) session.getAttribute("seats");
		
		if(seats != 0){
			flight.setSeats(seats);
		}
		flight.setSelectedClass(classType);
		
		//Set the flight as a session attribute
		session.setAttribute("flight", flight);
		
		//Encode URL
		String url = "/WEB-INF/ViewAndBook.jsp";
		url = response.encodeURL(url);
		
		//Forward to ViewAndBook.jsp
		RequestDispatcher rd = request.getRequestDispatcher(response.encodeURL(url));  
		rd.forward(request, response);
		
	}

}
